package io.hots.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.hots.config.RabbitMQConfig;
import io.hots.controller.request.ScanCodeRequest;
import io.hots.entity.*;
import io.hots.enums.BizCodeEnum;
import io.hots.exception.BizException;
import io.hots.feign.UserFeignService;
import io.hots.interceptor.LoginInterceptor;
import io.hots.mapper.ScanCodeMapper;
import io.hots.mapper.ScanCodeMappingMapper;
import io.hots.mq.CodeMessage;
import io.hots.service.ScanCodeService;
import io.hots.util.JsonUtil;
import io.hots.util.ResultData;
import io.hots.utils.IDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yueshibin@cetcbigdata.com
 * @date 2022/6/15 8:14 下午
 */
@Service
@Slf4j
public class ScanCodeServiceImpl implements ScanCodeService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RabbitMQConfig rabbitMQConfig;

    @Autowired
    UserFeignService userFeignService;

    @Autowired
    ScanCodeMapper scanCodeMapper;

    @Autowired
    ScanCodeMappingMapper scanCodeMappingMapper;


    @Override
    public void scanCodeSave(ScanCodeRequest request) {

        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Long accountNo = Long.parseLong(loginUser.getUserId());

        CodeMessage eventMessage = new CodeMessage(IDUtil.geneSnowFlakeID().toString(),accountNo,request);

        eventMessage.setMessageId(IDUtil.geneSnowFlakeID().toString());
        rabbitTemplate.convertAndSend(rabbitMQConfig.getScanCodeExchange(), rabbitMQConfig.getScanCodeRoutingKey(),eventMessage);

    }

    @Override
    @Transactional
    public void handlerCode(CodeMessage codeMessage) throws Exception {

        ScanCodeRequest request = JsonUtil.json2Obj(codeMessage.getContent(),ScanCodeRequest.class);


        UserEntity userEntity = this.getUser(request.getUserId());
        VenueEntity venueEntity = this.getVenue(request.getVenueId());
        ScanCodeEntity scanCodeEntity = new ScanCodeEntity(userEntity,venueEntity);

        scanCodeMapper.insert(scanCodeEntity);

        ScanCodeMappingEntity scanCodeMappingEntity = new ScanCodeMappingEntity(userEntity,venueEntity);

        scanCodeMappingMapper.insert(scanCodeMappingEntity);
    }

    @Override
    public ResultData queryUserVenueById(String userId) {
        List<ScanCodeEntity> scanCodeEntityList = scanCodeMapper.selectList(new QueryWrapper<ScanCodeEntity>().eq("user_id", userId));

        List<String> collect = scanCodeEntityList.stream().map(ScanCodeEntity::getVenueId).collect(Collectors.toList());

        return ResultData.buildSuccess(collect);
    }

    @Override
    public ResultData queryVenueUserById(String venueId) {
        List<ScanCodeMappingEntity> scanCodeMappingEntityList = scanCodeMappingMapper.selectList(new QueryWrapper<ScanCodeMappingEntity>().eq("venue_id", venueId));

        List<String> collect = scanCodeMappingEntityList.stream().map(ScanCodeMappingEntity::getUserId).collect(Collectors.toList());

        return ResultData.buildSuccess(collect);
    }

    private UserEntity getUser(String userId) throws Exception {
        //查询用户信息
        ResultData resultData = userFeignService.queryUserById(userId);
        UserEntity userEntity = null;
        if(resultData.getCode()==0){
            //正常响应，判断订单状态
            String user = resultData.getData().toString();
            userEntity = JsonUtil.json2Obj(user,UserEntity.class);
        }else {
            throw new BizException(BizCodeEnum.USER_QUERY_ERROR);
        }

        return userEntity;
    }

    private VenueEntity getVenue(String venueId) throws Exception {
        //查询场所信息
        ResultData resultData = userFeignService.queryVenueById(venueId);
        VenueEntity venueEntity = null;
        if(resultData.getCode()==0){
            //正常响应，判断订单状态
            String venue = resultData.getData().toString();
            venueEntity = JsonUtil.json2Obj(venue,VenueEntity.class);
        }else {
            throw new BizException(BizCodeEnum.VENUE_QUERY_ERROR);
        }

        return venueEntity;
    }

}
